package com.application.Activity;

import java.util.Stack;

import com.application.Controller.NetworkController;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.LocalActivityManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Window;

public class StackActivity extends ActivityGroup{

	private Stack<String> stack;

	  @Override
	  public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    if (stack == null) stack = new Stack<String>();
	    //start default activity
	    push("FrmSubject", new Intent(this, FrmSubject.class));
	  }

	  @Override
	  public void finishFromChild(Activity child) {
	    pop();
	  }

	  @Override
	  public void onBackPressed() {
			  pop();
	  }


	  public void push(String id, Intent intent) {
	    Window window = getLocalActivityManager().startActivity(id, intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
	    if (window != null) {
	      stack.push(id);
	      setContentView(window.getDecorView());
	    }
	  }

	  public void pop() {
	    if (stack.size() == 1) 
	    {
	    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setIcon(R.drawable.img_dialog);
			builder.setMessage("Bạn có chắc muốn thoát khỏi chương trình ?")
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int id) {
					if(!NetworkController.isOffline())
					{
						String s = NetworkController.get_ipHost();
						NetworkController.SendMessageLogout();
//						NetworkController.peerRelease();
						//xoá danh sách hàng xóm khi thoát khỏi ứng dụng
//						ReadWriteFileController.deleteFile(ReadWriteFileController.pathNeighborsList);
					}
					//NetworkController.SendMessageLogout(new Address("192.168.173.20:5033"));
					
					finish();
//					System.exit(0);
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int id) {
					 push("FrmSubject", new Intent(StackActivity.this, FrmSubject.class));
					dialog.cancel();
					
				}
			});
			AlertDialog alert = builder.create();
			alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255))); 
			alert.show();
	    }
	    LocalActivityManager manager = getLocalActivityManager();
	    manager.destroyActivity(stack.pop(), true);
	    if (stack.size() > 0) {
	      Intent lastIntent = manager.getActivity(stack.peek()).getIntent();
	      Window newWindow = manager.startActivity(stack.peek(), lastIntent);
	      setContentView(newWindow.getDecorView());
	    }
	  }
}
